#!/usr/bin/env perl

BEGIN {
	push @::INC,".." if -f "../pv3.pm";
	push @::INC,$::ENV{CODEMGR_LIBS} if exists($::ENV{CODEMGR_LIBS});
}

use pv3;
use Getopt::Long;
use File::Basename;
use strict;
use Config;

$::ARG_pv=undef;
$::ARG_force=0;
$::ARG_version=undef;

# Check out is different since it has to check the arg list
# looking for unresolved patterns (*) and match against database contents
# for pattern matches...

sub usage {
	print "
Usage: pv3_co [-f] [-p DIR] [-v VERSION] file ...

The pv3_co command allows a file being managed by the PV2 version
control system to be checked out ready for editing. It will 
lock the file to ensure no-one else checks out the same file.

At present it supports the following command line arguments:

-f   Force the check-out. If the contents of the file currently
     do not match any previously checked in version then this action by
     default is not allowed. This forces the check-out to continue
     in this particular case.
-p   By default the PV3 version file is thought to be in the
     current directory. Use this argument if the file is kept in
     a different location. This specifies the directory and filename.
-v   Indiciate the version to check out. If not specified a copy
     of the latest version is written to the current directory.

Note: If the file already exists in this directory it will 
      only be checked out if the file in question is read-only.

Written by Simon Edwards, (C) 2006-2010 www.advantsys.co.uk
";
	exit 1;
}

if(!GetOptions(
	"force"		=> \$::ARG_force,
	"pv=s"		=> \$::ARG_pv,
	"version=s"	=> \$::ARG_version,
	)) {
	usage;
}

if(defined($::ARG_pv)) {
	if(! -d dirname($::ARG_pv)) {
		mkdir dirname($::ARG_pv),0775 or die("Failed to create directory $::ARG_pv: $!");
	}
}

my %args=();
if(defined($::ARG_version)) {
	$args{VERSION}=$::ARG_version;
}
$args{FORCE}=1 if $::ARG_force;
@::CHECK_OUT_LIST=();

if($Config{osname} =~ /mswin/i) {
	my @F=();
	for my $cpat (@ARGV) {
		push @F,glob($cpat);
	}
	@ARGV=@F;
}

for my $cfile (@ARGV) {
	next if -d $cfile;
	next if $cfile =~ /,pv3$/;
	# We do not check for local only files, since it might
	# have been deleted from the local directory....
	push @::CHECK_OUT_LIST,$cfile;
}

if($Config{osname} =~ /mswin/i) {
	my @F=();
	for my $cpat (@ARGV) {
		push @F,glob($cpat);
	}
	@ARGV=@F;
}

{
	$args{PVFILE}=$::ARG_pv if defined($::ARG_pv);
	$args{CHECKOUT}=1; $args{LOCK}=1;
	my $res=pv3::get(FILE => [@::CHECK_OUT_LIST],%args);
	my $errors=0; my $oks=0;
	for my $c (@$res) {
		if($c->[0]==0) {
			$errors++;
			if(!defined($c->[2]) || !length($c->[2])) {
				print "ERROR: $c->[1]\n";
			} else {
				print "ERROR: $c->[2] - $c->[1]\n";
			}
		} else {
			$oks++;
			print "CO   : $c->[3] - $c->[2],$c->[1]\n";
		}
	}
}
exit(0);
